package com.yzq.utils;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 阿里云短信工具类
 */
@Slf4j
@Component
public class AliyunSmsUtils {

    @Value("${aliyun.sms.access-key-id}")
    private String accessKeyId;

    @Value("${aliyun.sms.access-key-secret}")
    private String accessKeySecret;

    @Value("${aliyun.sms.region-id}")
    private String regionId;

    @Value("${aliyun.sms.sign-name}")
    private String signName;

    @Value("${aliyun.sms.template-code}")
    private String templateCode;

    @Value("${aliyun.sms.endpoint-override}")
    private String endpointOverride;

    private AsyncClient client;

    @PostConstruct
    public void init() {
        // 配置凭据认证信息，包括 ak、secret、token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret)
                .build());

        // 配置客户端
        client = AsyncClient.builder()
                .region(regionId) // 地域ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
                                .setEndpointOverride(endpointOverride)
                )
                .build();
    }

    /**
     * 发送短信
     * @param phoneNumbers 手机号码
     * @param code 短信验证码
     * @return 发送结果
     */
    public SendSmsResponse sendSms(String phoneNumbers, String code) {
        try {
            log.info("开始发送短信...");
            log.info("手机号码: {}", phoneNumbers);
            log.info("短信验证码: {}", code);
            log.info("短信签名: {}", signName);
            log.info("短信模板CODE: {}", templateCode);

            // API请求的参数设置
            SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                    .signName(signName) // 短信签名名称
                    .templateCode(templateCode) // 短信模板CODE
                    .phoneNumbers(phoneNumbers) // 手机号码
                    .templateParam("{\"code\":\"" + code + "\"}") // 短信模板变量对应的实际值 例如 { "code": "1234" }
                    .build();

            // 异步获取API请求的返回值
            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
            // 同步获取API请求的返回值
            SendSmsResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));
            return resp;
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            System.err.println("短信发送失败: " + e.getMessage());
            return null;
        }
    }

    @PreDestroy
    public void close() {
        // 关闭客户端
        if (client != null) {
            client.close();
        }
    }
}
